package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.entity.Sales;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.Max;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        /**
         * 算日期
         */
        ArrayList<LocalDate> dateList = calculateDates(begin, end);

        String dateListString = StringUtils.join(dateList, ",");


        /**
         * 处理时间有问题
         * select sum(amount) from xxx where status = 完成 and order_time > ? and order_time <= ?;
         */
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);
            Double sum = orderMapper.sumByMap(map);
            sum = sum == null ? 0.0 : sum;
            turnoverList.add(sum);
        }
        String turnoverListString = StringUtils.join(turnoverList, ",");

        return TurnoverReportVO.builder()
                .dateList(dateListString)
                .turnoverList(turnoverListString)
                .build();
    }

    private static ArrayList<LocalDate> calculateDates(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        do {
            begin = begin.plus(1, ChronoUnit.DAYS);
            dateList.add(begin);
        } while (begin.isBefore(end));
        return dateList;
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        /**
         * 算日期
         */
        ArrayList<LocalDate> dateList = calculateDates(begin, end);
        String dateListString = StringUtils.join(dateList, ",");

        /**
         * 每日查询新增用户 ， 查询每日用户总数
         */
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            /**
             * select count(*) from user where create_time < end_time and create_time > begin_time
             */
            /**
             * 查询每日用户总数
             */
            Map map = new HashMap();
            map.put("endTime", endTime);
            Integer sum = userMapper.sumByMap(map);
            sum = sum == null ? 0 : sum;
            totalUserList.add(sum);

            /**
             * 再多查询一个参数，就可以每日新增用户数量
             */
            map.put("beginTime", beginTime);
            sum = userMapper.sumByMap(map);
            sum = sum == null ? 0 : sum;
            newUserList.add(sum);
        }
        String newUserListString = StringUtils.join(newUserList, ",");
        String totalUserListString = StringUtils.join(totalUserList, ",");

        return UserReportVO.builder()
                .dateList(dateListString)
                .newUserList(newUserListString)
                .totalUserList(totalUserListString)
                .build();
    }

    /**
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistic(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dateList = calculateDates(begin, end);
        String dateListString = StringUtils.join(dateList, ",");
        /**
         * select count (*) from orders where order_time < endTime and order_time > beginTime
         */
        Map map = new HashMap();
        ArrayList<Integer> orderCountList = new ArrayList<>();
        ArrayList<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            /**
             * 今日订单总数
             * select count(*) from user where create_time < end_time and create_time > begin_time
             */
            Integer orderCount = orderMapper.countByMap(map);
            orderCount = orderCount == null ? 0 : orderCount;
            orderCountList.add(orderCount);
            /**
             * 今日有效订单数量
             * select count(*) from user where create_time < end_time and create_time > begin_time and status = #{已完成}
             */
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countByMap(map);
            validOrderCount = validOrderCount == null ? 0 : validOrderCount;
            validOrderCountList.add(validOrderCount);

        }

        /**
         * 算总数
         */
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate = totalOrderCount == 0 ? 0.0 : 1.0 * validOrderCount / totalOrderCount;

        /**
         * 转换字符
         */
        String validOrderCountListString = StringUtils.join(validOrderCountList, ",");
        String orderCountListString = StringUtils.join(orderCountList, ",");


        return OrderReportVO.builder()
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCountList(orderCountListString)
                .validOrderCountList(validOrderCountListString)
                .orderCompletionRate(orderCompletionRate)
                .dateList(dateListString)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        /**
         * select name,count(*) as num from order_detail
         * left join orders on order_detail.order_id = orders.id
         * where orderTime > beginTime and order_time < endTime and status = 5
         * group by name
         * order by num desc
         * limit 0,10
         */

        Map map =new HashMap();
        map.put("beginTime",LocalDateTime.of(begin,LocalTime.MIN));
        map.put("endTime",LocalDateTime.of(end, LocalTime.MAX));
        map.put("status",Orders.COMPLETED);
        List<Sales> sales = orderDetailMapper.topDishes(map);

        for (Sales s : sales){
            nameList.add(s.getDishName());
            numberList.add(s.getNum());
        }

        String nameListString = StringUtils.join(nameList, ",");
        String numberListString = StringUtils.join(numberList, ",");
        return SalesTop10ReportVO.builder()
                .nameList(nameListString)
                .numberList(numberListString)
                .build();
    }
}
